package com.lanou3g.hw0419.q3;

import java.io.*;

/**
 * If there are no bugs, it was created by Chen FengYao on 2018/4/20;
 * Otherwise, I don't know who created it either
 */

public class Main {
    public static void main(String[] args) {
        String rootPath = "C:\\Users\\73448\\Desktop\\作业\\Q2";
        String targetPath = "C:\\Users\\73448\\Desktop\\作业\\Q3";
        File file = new File(rootPath);
        for (File file1 : file.listFiles()) {
            if (file1.isFile() &&
                    file1.length() >= 1024 * 1024 * 1024) {
                split(file1, targetPath);
            }
        }
    }

    /**
     * 拆分
     *
     * @param file       要拆的文件
     * @param targetPath 拆完放哪 --Q3文件夹
     */
    public static void split(File file, String targetPath) {
        File targetDir = new File(targetPath, file.getName());
        // 创建文件夹
        targetDir.mkdirs();

        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        int index = 0;//第几个文件

        try {
            bis = new BufferedInputStream(
                    new FileInputStream(file));
            int pos = 0;
            byte[] buf = new byte[1024];

            File desFile = new File(targetDir,
                    file.getName() + index);
            bos = new BufferedOutputStream(
                    new FileOutputStream(desFile));
            long size = 0;
            while ((pos = bis.read(buf)) != -1) {
                // 写流
                bos.write(buf, 0, pos);
                size += pos;
                // 每写400M bos就指向新的文件
                if (size >= 400 * 1024 * 1024) {
                    bos.close();//把原来的流关了
                    index++;//下一个文件
                    size = 0;// 大小重新统计
                    // bos 指向新的文件
                    bos = new BufferedOutputStream(
                            new FileOutputStream(
                                    new File(targetDir,
                                            file.getName() + index)));
                }
            }
            // while 循环外面,别写错大括号位置了
            bos.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }
}
